package com.yhcui.monitor.grpc;

import com.yhcui.monitor.bean.OsInfo;
import com.yhcui.monitor.bean.Result;
import com.yhcui.monitor.logic.OsInfoLogic;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

/**
 * 此处代码可以进行优化
 * 1、支持发送邮件
 * 2、支持分批设置发送开关
 * 3、支持增加发送策略
 */
@GrpcService
@Slf4j
public class MonitorGrpcGrpcServer extends MonitorGrpcGrpc.MonitorGrpcImplBase {


    @Autowired
    private OsInfoLogic osInfoLogic;

    @Override
    public void osInfo(Monitor.OsInfoRequest request,
                       io.grpc.stub.StreamObserver<Monitor.OsInfoResponse> responseObserver) {
        log.info("osinfo:{}",request.toString());
        Monitor.OsInfoResponse osInfoResponse = null;
        if (StringUtils.hasText(request.getIp())) {
            OsInfo osInfo = buildOsInfo(request);
            Result result = osInfoLogic.analysisOsInfo(osInfo);
            osInfoResponse = Monitor.OsInfoResponse.newBuilder().setStatus(result.getStatus()).build();
        } else {
            osInfoResponse = Monitor.OsInfoResponse.newBuilder().setStatus(500).build();
        }
        responseObserver.onNext(osInfoResponse);
        responseObserver.onCompleted();
    }

    @Override
    public void cupInfo(Monitor.OsInfoRequest request,
                        io.grpc.stub.StreamObserver<Monitor.OsInfoResponse> responseObserver) {
        log.info("cupInfo:{}",request.toString());
        Monitor.OsInfoResponse osInfoResponse = null;
        OsInfo osInfo = buildOsInfo(request);
        Result result = osInfoLogic.analysisCpuInfo(osInfo);
        osInfoResponse = Monitor.OsInfoResponse.newBuilder().setStatus(result.getStatus()).build();
        responseObserver.onNext(osInfoResponse);
        responseObserver.onCompleted();
    }

    private OsInfo buildOsInfo(Monitor.OsInfoRequest request) {
        // 采用BeanUtils xx.copy是不是更好一些
        return OsInfo.builder()
                .ip(request.getIp())
                .cpuUsedPercent(request.getCpuUsedPercent())
                .load1(request.getLoad1())
                .load5(request.getLoad5())
                .load15(request.getLoad15())
                .memUsedPercent(request.getMemUsedPercent())
                .swapTotal(request.getSwapTotal())
                .swapFree(request.getSwapFree())
                .numCPU(request.getNumCPU())
                .diskUsedPercent(request.getDiskUsedPercent()).build();
    }
}
